package com.zlp.design.singleton.v8;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {
    public static void main(String[] args) throws Exception {
        //往文件中写对象
        writeObject2File();
        //从文件中读取对象
        Singleton01 s1 = readObjectFromFile();
        Singleton01 s2 = readObjectFromFile();

        //判断两个反序列化后的对象是否是同一个对象
        System.out.println(s1 == s2);
    }

    private static Singleton01 readObjectFromFile() throws Exception {
        //创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\file\\aaa.txt"));
        //第一个读取Singleton对象
        Singleton01 instance = (Singleton01) ois.readObject();
        System.out.println(instance);
        ois.close();
        return instance;
    }

    public static void writeObject2File() throws Exception {
        //获取Singleton类的对象
        Singleton01 instance = Singleton01.getInstance();
        //创建对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\file\\aaa.txt"));
        //将instance对象写出到文件中
        oos.writeObject(instance);
        oos.flush();
        oos.close();
    }
}